package com.javaboy.vhr.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author: gaoyang
 * @date: 2020-12-27 11:44
 * @description: 判断当前用户是否具备角色
 */
@Slf4j
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {

    /**
     *
     * @param authentication 包含了当前的用户信息，包括拥有的权限。
     *                       这里的权限来源就是前面登录时UserDetailsService中设置的authorities。
     * @param object FilterInvocation对象，可以得到request等web资源。
     * @param configAttributes 本次访问需要的权限。
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
            throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute:configAttributes){
            // 需要的角色
            String needRole = configAttribute.getAttribute();
            if("ROLE_LOGIN".equals(needRole)){
                if (authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("尚未登录，请登录!");
                }else {
                    return;
                }
            }
            // 获取当前登录用户的角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

            for (GrantedAuthority authority:authorities) {
                // 判断是否具备当前登录的角色，如果有需要的角色或者是系统管理员则返回
                if (authority.getAuthority().equals(needRole) || authority.getAuthority().equals("ROLE_admin")){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
